package org.spring.springboot.app.adv.advmobilemaininfo.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.springboot.app.adv.advarea.dao.AdvAreaDao;
import org.spring.springboot.app.adv.advarea.domain.po.AdvAreaPO;
import org.spring.springboot.app.adv.advarea.service.IAdvAreaService;
import org.spring.springboot.app.adv.advexam.domain.po.AdvExamPO;
import org.spring.springboot.app.adv.advexam.service.IAdvExamService;
import org.spring.springboot.app.adv.advmobilemaininfo.dao.AdvMobileMainInfoDao;
import org.spring.springboot.app.adv.advmobilemaininfo.domain.po.AdvMobileMainInfoPO;
import org.spring.springboot.app.adv.advmobilemaininfo.domain.vo.*;
import org.spring.springboot.app.adv.advmobilemaininfo.service.IAdvMobileMainInfoService;
import org.spring.springboot.app.adv.advinfo.dao.AdvInfoDao;
import org.spring.springboot.app.adv.advinfo.domain.po.AdvInfoPO;
import org.spring.springboot.app.agent.balancelog.domain.po.SysOfficeBalanceLogPO;
import org.spring.springboot.app.agent.balancelog.service.ISysOfficeBalanceLogService;
import org.spring.springboot.app.base.Constants;
import org.spring.springboot.app.base.R;
import org.spring.springboot.app.base.User;
import org.spring.springboot.app.platform.balancelog.service.IPlatformBalanceLogService;
import org.spring.springboot.app.sys.office.domain.po.SysOfficeWalletPO;
import org.spring.springboot.app.sys.office.service.ISysOfficeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class AdvMobileMainInfoServiceImpl implements IAdvMobileMainInfoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AdvMobileMainInfoServiceImpl.class);

    @Autowired
    private AdvMobileMainInfoDao advMobileMainInfoDao;
    @Autowired
    private AdvInfoDao advInfoDao;
    @Autowired
    private ISysOfficeService sysOfficeService;
    @Autowired
    private IAdvExamService advExamService;
    @Autowired
    private IAdvAreaService advAreaService;
    @Autowired
    private IPlatformBalanceLogService platformBalanceLogService;


    @Override
    public AdvMobileMainInfoPO find(String id) {
        return advMobileMainInfoDao.selectByPrimaryKey(id);
    }

    @Override
    public R delete(String id) {
        R r = new R();
        AdvInfoPO mainPo = new AdvInfoPO();
        mainPo.setId(id);
        mainPo.preDelete();
        if (advInfoDao.updateByPrimaryKeySelective(mainPo) == 0) {
            return r.fail().setMessage("保存失败");
        }
        AdvMobileMainInfoPO po = new AdvMobileMainInfoPO();
        po.setId(id);
        po.preDelete();
        if (advMobileMainInfoDao.updateByPrimaryKeySelective(po) == 0) {
            return r.fail().setMessage("保存失败");
        }
        return r.success();
    }


    @Override
    public List<AdvMobileMainInfoPO> findPage(AdvMobileMainInfoSearchVO searchVO, int pageNum, int pageSize) {
        return advMobileMainInfoDao.findPage(searchVO, pageNum,pageSize);
    }

    @Override
    @Transactional
    public R saveInfo(AdvMobileMainInfoSaveInVO vo, User user) {
        R r = new R();
        double eachPlatform = 0.02;
        double eachCommision = 0.2;
        int alldays = vo.getZoneDay();
        int totalCount = alldays;
        BigDecimal eachPlatformMo= new BigDecimal(eachPlatform);
        BigDecimal allPlatformMo= eachPlatformMo.multiply(new BigDecimal(alldays));
        BigDecimal eachCommisionMo= new BigDecimal(eachCommision);
        BigDecimal allCommisionMo= eachCommisionMo.multiply(new BigDecimal(alldays));

        BigDecimal payMo = allPlatformMo.add(allCommisionMo);
        //保存主表
        AdvInfoPO mainPO = new AdvInfoPO();
        mainPO.setOfficeId(user.getOfficeId());
        mainPO.setType(Constants.ADV_INFO_TYPE_1);
        mainPO.setIsSystem(0);
        mainPO.setTitle(vo.getTitle());
        mainPO.setPhotos(vo.getPhotos());
        mainPO.setStartDate(vo.getStartDate_());
        mainPO.setEndDate(vo.getEndDate_());
        mainPO.setPayState(Constants.ADV_INFO_TYPE_PAY_STATE_1);
        mainPO.setPayMo(payMo);
        mainPO.setContent(vo.getContent());
        mainPO.preInsert();
        if (advInfoDao.insertSelective(mainPO) <1) {
            throw new RuntimeException("保存活动主表失败");
        }
        //保存副表
        AdvMobileMainInfoPO MobileMainInfoPO = new AdvMobileMainInfoPO();
        MobileMainInfoPO.setAllDays(alldays);
        MobileMainInfoPO.setEachPlatformMo(eachPlatformMo);
        MobileMainInfoPO.setAllPlatformMo(allPlatformMo);
        MobileMainInfoPO.setEachCommisionMo(eachCommisionMo);
        MobileMainInfoPO.setAllCommisionMo(allCommisionMo);
        MobileMainInfoPO.setTotalCount(totalCount);
        MobileMainInfoPO.setViewCount(0);
        MobileMainInfoPO.preInsert();
        MobileMainInfoPO.setId(mainPO.getId());
        if (advMobileMainInfoDao.insertSelective(MobileMainInfoPO) <1) {
            throw new RuntimeException("保存活动副表失败");
        }
        //保存区域
        advAreaService.saveAreas(mainPO.getId(),vo.getAreaIds());

        AdvMobileMainInfoSaveOutVO outVO = new AdvMobileMainInfoSaveOutVO();
        outVO.setId(mainPO.getId());
        outVO.setPayMo(mainPO.getPayMo());
        return r.success().setData(outVO);
    }



    @Override
    public R updateInfo(AdvMobileMainInfoUpdateInVO vo) {
        R r = new R();
        //判断广告是否审核（审核之前可以修改）
        AdvMobileMainInfoPO MobileMainInfoPO = advMobileMainInfoDao.selectByPrimaryKey(vo.getId());
        if (MobileMainInfoPO.getExamState() != null && MobileMainInfoPO.getExamState().intValue() == Constants.ADV_EXAM_STATE_2) {
            return r.fail().setMessage("已审核广告不能修改");
        }

        //保存主表
        AdvInfoPO mainPo = new AdvInfoPO();
        mainPo.setId(vo.getId());
        mainPo.setTitle(vo.getTitle());
        mainPo.setContent(vo.getContent());
        mainPo.setPhotos(vo.getPhotos());
        mainPo.preUpdate();
        if (advInfoDao.updateByPrimaryKeySelective(mainPo) <1) {
            return r.fail().setMessage("修改活动主表失败");
        }

        if (StringUtils.isNotBlank(vo.getAreaIds())) {
            //删除区域
            advAreaService.deleteByAdvId(mainPo.getId());
            //保存区域
            advAreaService.saveAreas(mainPo.getId(),vo.getAreaIds());
        }
        return r.success();
    }



    @Override
    @Transactional
    public R pay(String id, User user) {
        R r = new R();
        AdvInfoPO mainPO = advInfoDao.selectByPrimaryKey(id);
        //判断支付状态
        if (mainPO.getPayState().intValue() == Constants.ADV_INFO_TYPE_PAY_STATE_2) {
            return r.fail().setMessage("活动已经支付");
        }
        //比对机构金额和广告费用
        SysOfficeWalletPO walletPO = sysOfficeService.queryWallet(user.getOfficeId());
        BigDecimal balance = walletPO.getBalance();
        BigDecimal payMo = mainPO.getPayMo();
        if (payMo.compareTo(balance) > 0) {
            return  r.fail().setMessage("余额不足");
        }
        //扣除机构费用
        sysOfficeService.subOfficeMo(user.getOfficeId(),payMo,Constants.SYS_OFFICE_BALANCE_LOG_TYPE_104,id,null,mainPO.getTitle());
        //添加审核表
        advExamService.addExam(user.getOfficeId(),id);
        //修改广告状态
        mainPO.setPayState(Constants.ADV_INFO_TYPE_PAY_STATE_2);
        mainPO.preUpdate();
        if (advInfoDao.updateByPrimaryKeySelective(mainPO) < 1) {
            throw new RuntimeException("更新活动主表失败");
        }
        return r.success();
    }

    @Override
    public int profitDivision(String advId) {
        AdvMobileMainInfoPO po = advMobileMainInfoDao.selectByPrimaryKey(advId);
        AdvInfoPO mainPO = advInfoDao.selectByPrimaryKey(advId);
        if (po == null || po.getIsProfit() == 1) {
            return 0;
        }
        po.setIsProfit(1);
        po.preUpdate();
        if (advMobileMainInfoDao.updateByPrimaryKeySelective(po) < 1) {
            throw new RuntimeException("更新活动副表失败");
        }
        BigDecimal eachPlatformMo = po.getEachPlatformMo();
        BigDecimal allPlatformMo = po.getAllPlatformMo();
        BigDecimal eachCommisionMo = po.getEachCommisionMo();
        BigDecimal allCommisionMo = po.getAllCommisionMo();
        //平台服务费
        if (allPlatformMo.compareTo(BigDecimal.ZERO) == 1) {
            platformBalanceLogService.addBalanceLog(allCommisionMo,Constants.PLATFORM_BALANCE_LOG_TYPE_102,advId,null,mainPO.getTitle());
        }
        return 1;
    }

    @Override
    public R saveSystemInfo(AdvMobileMainInfoSystemSaveInVO vo, User user) {
        R r = new R();

        //保存主表
        AdvInfoPO mainPO = new AdvInfoPO();
        mainPO.setOfficeId(user.getOfficeId());
        mainPO.setType(Constants.ADV_INFO_TYPE_1);
        mainPO.setIsSystem(1);
        mainPO.setTitle(vo.getTitle());
        mainPO.setPhotos(vo.getPhotos());
        mainPO.setStartDate(vo.getStartDate_());
        mainPO.setEndDate(vo.getEndDate_());
        mainPO.setPayState(Constants.ADV_INFO_TYPE_PAY_STATE_0);
        mainPO.setPayMo(null);
        mainPO.setContent(vo.getContent());
        mainPO.preInsert();
        if (advInfoDao.insertSelective(mainPO) <1) {
            throw new RuntimeException("保存活动主表失败");
        }
        //保存副表
        AdvMobileMainInfoPO MobileMainInfoPO = new AdvMobileMainInfoPO();
        MobileMainInfoPO.setAllDays(0);
        MobileMainInfoPO.setEachPlatformMo(null);
        MobileMainInfoPO.setAllPlatformMo(null);
        MobileMainInfoPO.setEachCommisionMo(null);
        MobileMainInfoPO.setAllCommisionMo(null);
        MobileMainInfoPO.setTotalCount(0);
        MobileMainInfoPO.setViewCount(0);
        MobileMainInfoPO.preInsert();
        MobileMainInfoPO.setId(mainPO.getId());
        if (advMobileMainInfoDao.insertSelective(MobileMainInfoPO) <1) {
            throw new RuntimeException("保存活动副表失败");
        }
        return r.success();
    }


}
